import logging
import time
import allure
from appium import webdriver
from appium.webdriver import WebElement
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.webdriver import WebDriver
from typing import List

"""
基类
"""


class Base:

    def __init__(self, driver_base: WebDriver = None):

        if not driver_base:
            caps = dict()
            caps['platformName'] = "android"
            caps['appPackage'] = "com.tencent.wework"
            caps['appActivity'] = ".launch.LaunchSplashActivity"
            caps['noReset'] = "true"
            caps['deviceName'] = "Clifford"
            # 加速启动
            caps['skipDeviceInitialization'] = 'true'
            caps['settings[waitForIdleTimeout'] = 0
            caps['dontStopAppOnReset'] = True

            logging.info("实例化driver对象")
            self.driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
            self.driver.implicitly_wait(5)

        else:
            self.driver = driver_base

    def find(self, by, locator) -> WebElement:
        """
        获取单个元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_element(by, locator)

    def find_with_scroll(self, text: str) -> WebElement:
        self.driver.implicitly_wait(10)
        element = self.driver.find_element(MobileBy.ANDROID_UIAUTOMATOR,
                                 f'new UiScrollable(new UiSelector().scrollable(true).\
                                 instance(0)).scrollIntoView(new UiSelector().\
                                 text("{text}").instance(0));')
        self.driver.implicitly_wait(5)
        return element

    def finds(self, by, locator) -> List[WebElement]:
        """
        获取一组元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_elements(by, locator)

    def find_and_click(self, by, locator) -> WebElement:
        """
        获取并点击元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        element = self.driver.find_element(by, locator)
        element.click()
        return element

    def do_screenshot(self, desc: str):
        timestamp = int(time.time())
        self.driver.save_screenshot(f"../pics/screenshot_{timestamp}.png")
        allure.attach.file(f"../pics/screenshot_{timestamp}.png", name=desc, attachment_type=allure.attachment_type.PNG)

    def close_driver(self):
        logging.info("关闭driver")
        self.driver.close()
